package com.example.helper2;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;
import java.util.List;

public class rumour_card_database extends SQLiteOpenHelper {
    public rumour_card_database(Context context){
        super(context,"rumourcardDB.db",null,1);
    }
    public void onCreate(SQLiteDatabase sqLiteDatabase){
        String sql = "create table rumourcard(id integer primary key autoincrement," +
                "rumourId varchar(20),date varchar(20),title varchar(100),abstractText varchar(100))";
        sqLiteDatabase.execSQL(sql);
    }
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int il){

    }

    public void adddata(SQLiteDatabase sqLiteDatabase,String rumourId,String date,String title,String abstractText){
        ContentValues values = new ContentValues();
        values.put("rumourId",rumourId);
        values.put("date",date);
        values.put("title",title);
        values.put("abstractText",abstractText);
        sqLiteDatabase.insert("rumourcard",null,values);
    }
    // 查找所有数据
    public List<RumourCardInfo> querydata(SQLiteDatabase sqLiteDatabase){
        Cursor cursor = sqLiteDatabase.query("rumourcard",null,null,null,null,null,"id ASC");
        List<RumourCardInfo> list = new ArrayList<>();
        while (cursor.moveToNext()){
            int id = cursor.getInt(cursor.getColumnIndex("id"));
            String rumourId = cursor.getString(1);
            String date = cursor.getString(2);
            String title = cursor.getString(3);
            String abstractText = cursor.getString(4);
            list.add(new RumourCardInfo(rumourId,id,date,title,abstractText));
        }
        cursor.close();
        sqLiteDatabase.close();
        return list;
    }
    // 根据id的值查找数据
    public RumourCardInfo querydatabyid(SQLiteDatabase sqLiteDatabase, int position){
        RumourCardInfo cardInfo = null;
        Cursor cursor = sqLiteDatabase.query("rumourcard",
                null,
                "id=?",
                new String[]{position+""},
                null,
                null,
                "id ASC");
        if (cursor.getCount() > 0){
            cursor.moveToFirst();
            int id = cursor.getInt(cursor.getColumnIndex("id"));
            String rumourId = cursor.getString(1);
            String title = cursor.getString(3);
            String abstractText = cursor.getString(4);
            String date = cursor.getString(2);
            cardInfo = new RumourCardInfo(rumourId,id,date,title,abstractText);
        }
        cursor.close();
        sqLiteDatabase.close();
        return cardInfo;
    }
}
